//
//  DownLoadOpration.m
//  断点下载PDF
//
//  Created by 徐凯 on 16/5/13.
//  Copyright © 2016年 cqjtu. All rights reserved.
//

#import "DownLoadOpration.h"

@implementation DownLoadOpration

- (void) initWithDownloadObject: (WHC_DownloadObject*) object index:(NSInteger) index{
    
    _downloadObject = object;
    self.index = index;
    if (_downloadObject.downloadState == WHCNone ||
        _downloadObject.downloadState == WHCDownloading ) {
        _downloadObject.downloadState = WHCDownloadWaitting;
    }
    WHC_DownloadOperation * operation = [[WHC_HttpManager shared] replaceCurrentDownloadOperationDelegate:self fileName:_downloadObject.fileName];
    if ([[WHC_HttpManager shared] existDownloadOperationTaskWithFileName:_downloadObject.fileName]) {
        if (_downloadObject.downloadState == WHCDownloadCanceled) {
            _downloadObject.downloadState = WHCDownloadWaitting;
            WHC_DownloadOperation * operation = [[WHC_HttpManager shared] download:_downloadObject.downloadPath
                                                                          savePath:[WHC_DownloadObject pdfDirectory]
                                                                      saveFileName:_downloadObject.fileName delegate:self];
            operation.index = self.index;
            if (_delegate && [_delegate respondsToSelector:@selector(updateDownloadValue: index:)]) {
                [_delegate updateDownloadValue:_downloadObject index:operation.index];
            }

        }
    }
    operation.index = index;
    
}

- (void) clickElmentReponse{
    
    switch (_downloadObject.downloadState) {
            
        case WHCDownloading:
            _downloadObject.downloadState = WHCDownloadCanceled;
          [[WHC_HttpManager shared] cancelDownloadWithFileName:_downloadObject.fileName deleteFile:NO];
            break;
            
        case WHCDownloadCanceled:{
            _downloadObject.downloadState = WHCDownloadWaitting;
            WHC_DownloadOperation * operation = [[WHC_HttpManager shared] download:_downloadObject.downloadPath
                                                                          savePath:[WHC_DownloadObject pdfDirectory]
                                                                      saveFileName:_downloadObject.fileName delegate:self];
            operation.index = self.index;
            if (_delegate && [_delegate respondsToSelector:@selector(updateDownloadValue: index:)]) {
                [_delegate updateDownloadValue:_downloadObject index:operation.index];
            }
            }
            break;
            
        case WHCDownloadWaitting:
            break;
        case WHCDownloadCompleted:
            break;
        default:
            break;
    }
}

- (void)saveDownloadState:(WHC_DownloadOperation *)operation {
    
    _downloadObject.currentDownloadLenght = operation.recvDataLenght;
    _downloadObject.totalLenght = operation.fileTotalLenght;
    [_downloadObject writeDiskCache];
    
}

#pragma mark - WHC_DownloadDelegate
- (void)WHCDownloadResponse:(nonnull WHC_DownloadOperation *)operation
                      error:(nullable NSError *)error
                         ok:(BOOL)isOK {
    if (isOK) {
        if (self.index == operation.index) {
            _downloadObject.downloadState = WHCDownloading;
            _downloadObject.currentDownloadLenght = operation.recvDataLenght;
            _downloadObject.totalLenght = operation.fileTotalLenght;
            //[self updateDownloadValue];
        }else {
            WHC_DownloadObject * tempDownloadObject = [WHC_DownloadObject readDiskCache:operation.strUrl];
            if (tempDownloadObject != nil) {
                tempDownloadObject.downloadState = WHCDownloading;
                tempDownloadObject.currentDownloadLenght = operation.recvDataLenght;
                tempDownloadObject.totalLenght = operation.fileTotalLenght;
                [tempDownloadObject writeDiskCache];
                if (_delegate && [_delegate respondsToSelector:@selector(updateDownloadValue: index:)]) {
                    [_delegate updateDownloadValue:tempDownloadObject index:operation.index];
                }
            }
        }
    }else {
        _downloadObject.downloadState = WHCNone;
        if (_delegate &&
            [_delegate respondsToSelector:@selector(pdfDownload:index:strUrl:)]) {
            [_delegate pdfDownload:error index:_index strUrl:operation.strUrl];
        }
    }
}

- (void)WHCDownloadProgress:(nonnull WHC_DownloadOperation *)operation
                       recv:(uint64_t)recvLength
                      total:(uint64_t)totalLength
                      speed:(nullable NSString *)speed {
    
    if (operation.index == self.index) {
        if (_downloadObject.totalLenght < 10) {
            _downloadObject.totalLenght = totalLength;
        }
        _downloadObject.currentDownloadLenght = recvLength;
        _downloadObject.downloadSpeed = speed;
        _downloadObject.downloadState = WHCDownloading;
        NSLog(@"下载进度%llu",recvLength);
        [_delegate downloadProgress:_downloadObject index:operation.index];
    }
}

- (void)WHCDownloadDidFinished:(nonnull WHC_DownloadOperation *)operation
                          data:(nullable NSData *)data
                         error:(nullable NSError *)error
                       success:(BOOL)isSuccess {
    
    if (isSuccess) {
        
        if (self.index == operation.index) {
            _downloadObject.downloadState = WHCDownloadCompleted;
            _downloadObject.downloadTimeString = [DateTimeUtil currentDataTime:@"YYYY-MM-dd HH:mm:ss"];
            [self saveDownloadState:operation];
        }else {
            WHC_DownloadObject * tempDownloadObject = [WHC_DownloadObject readDiskCache:operation.strUrl];
            if (tempDownloadObject != nil) {
                tempDownloadObject.downloadState = WHCDownloadCompleted;
                tempDownloadObject.currentDownloadLenght = operation.recvDataLenght;
                tempDownloadObject.totalLenght = operation.fileTotalLenght;
                tempDownloadObject.downloadTimeString = [DateTimeUtil currentDataTime:@"YYYY-MM-dd HH:mm:ss"];
                [tempDownloadObject writeDiskCache];
                if (_delegate && [_delegate respondsToSelector:@selector(updateDownloadValue:index:)]) {
                    [_delegate downloadFinish:tempDownloadObject index:operation.index];
                }
            }
        }
    }else {
        
        WHC_DownloadObject * tempDownloadObject;
        if (self.index == operation.index) {
            _downloadObject.downloadState = WHCDownloadCanceled;
        }else {
            tempDownloadObject = [WHC_DownloadObject readDiskCache:operation.strUrl];
            if (tempDownloadObject != nil) {
                tempDownloadObject.downloadState = WHCDownloadCanceled;
            }
        }
        if (error != nil &&
            error.code == WHCCancelDownloadError &&
            !operation.isDeleted) {
            if (self.index == operation.index) {
                [self saveDownloadState:operation];
            }else {
                if (tempDownloadObject != nil) {
                    tempDownloadObject.currentDownloadLenght = operation.recvDataLenght;
                    tempDownloadObject.totalLenght = operation.fileTotalLenght;
                    [tempDownloadObject writeDiskCache];
                }
                
            }
            [self saveDownloadState:operation];
        }else {
            [[[UIAlertView alloc] initWithTitle:@"下载失败" message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
        }
        if (tempDownloadObject != nil) {
            if (_delegate && [_delegate respondsToSelector:@selector(updateDownloadValue:index:)]) {
                [_delegate downloadFinish:tempDownloadObject index:operation.index];
            }
        }
    }
    if (self.index == operation.index) {
       // [self updateDownloadValue];
        [_delegate downloadFinish:_downloadObject index:_index];
    }
}



@end
